package _interview150;

import java.util.*;

/**
 * 15. 三数之和
 */
public class No15 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int target = -nums[i];
            if (nums[i + 1] + nums[i + 2] > target) break; // 优化一
            if (nums[n - 2] + nums[n - 1] < target) continue; // 优化二
            int left = i + 1, right = n - 1;
            while (left < right) {
                if (nums[left] + nums[right] < target) left++;
                else if (nums[left] + nums[right] > target) right--;
                else {
                    ans.add(List.of(-target, nums[left], nums[right]));
                    while (left < right && nums[left++] == nums[left]) ;
                    while (left < right && nums[right--] == nums[right]) ;
                }
            }
        }
        return ans;
    }
}
